﻿namespace GZipDemo
{
    using System;
    using System.Windows;
    using System.Xml.Linq;
    using Microsoft.Phone.Controls;
    using Resources;
    using WP7Contrib.Communications;
    using WP7Contrib.Logging;

    public partial class MainPage : PhoneApplicationPage
    {
        private string requestUrl = "http://api.nestoria.co.uk/api?action=search_listings&version=&encoding=json&page=1&number_of_results=30&withimage_only=0&keywords=&keywords_exclude=&place_name=N16&property_type=&listing_type=buy&bedroom_min=min&bedroom_max=max&bathroom_min=min&bathroom_max=max&room_min=min&room_max=max&price_min=min&price_max=max&sort=bedroom_lowhigh";

        private readonly IHandleResourcesFactory resourceClientFactory;
        private readonly ILog log;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            this.log = new DebugLog();
            this.resourceClientFactory = new ResourceClientFactory(log);
        }

        private void HanldeNoGzipButtonClick(object sender, RoutedEventArgs e)
        {
            this.resourceClientFactory.Create()
                .UseUrlForGet(requestUrl)
                .ForType(ResourceType.Json)
                .Get<Result>()
                .Subscribe(result =>
                               {
                                   this.log.Write("SUCCEEDED!");
                                   this.log.Write("Listing count = " + result.Response.Listings.Count);
                               },
                           exception => this.log.Write("FAILED!"));
        }

        private void HandleGzipButtonClick(object sender, RoutedEventArgs e)
        {
            this.resourceClientFactory.Create()
               .UseUrlForGet(requestUrl)
               .ForType(ResourceType.Json)
               .WithGzip()
               .Get<Result>()
               .Subscribe(result =>
                              {
                                  this.log.Write("SUCCEEDED!");
                                  this.log.Write("Listing count = " + result.Response.Listings.Count);
                              },
                          exception => this.log.Write("FAILED!"));
        }
    }
}